<?php
/**
 * 注释不留名,代码随便用
 */

namespace app\common\library\basicadmin\logic;

use app\common\controller\BasicAdmin;
use app\common\library\basicadmin\Logic;
use think\Model;

/**
 * 表单视图管理器
 * Class Form
 * @package library\logic
 */
class Form extends Logic
{
    /**
     * 表单模板文件
     * @var string
     */
    protected $tpl;

    /**
     * 表单扩展数据
     * @var array
     */
    protected $data;

    /**
     * 表单额外更新条件
     * @var array
     */
    protected $where;

    /**
     * 数据对象主键名称
     * @var array|string
     */
    protected $pkField;

    /**
     * 数据对象主键值
     * @var string
     */
    protected $pkValue;

    /**
     * Form constructor.
     * @param Model
     * @param string $tpl 模板名称
     * @param string $pkField 指定数据对象主键
     * @param array $where 额外更新条件
     * @param array $data 表单扩展数据
     */
    public function __construct(Model $model, $tpl = '', $pkField = '', $where = [], $data = [])
    {
        $this->model = $model;
        list($this->tpl, $this->where, $this->data) = [$tpl, $where, $data];
        $this->pkField = empty($pkField) ? ($this->model->getPk() ? $this->model->getPk() : 'id') : $pkField;;
        $this->pkValue = input($this->pkField, isset($data[$this->pkField]) ? $data[$this->pkField] : null);
        parent::__construct();
    }

    public function init(BasicAdmin $controller, $data = [])
    {
        $this->controller = $controller;
        // GET请求, 获取数据并显示表单页面
        if ($this->request->isGet()) {
            if ($this->pkValue !== null) {
                $where = [$this->pkField => $this->pkValue];
                $model = $this->model;
                $data = $model->where($where)->where($this->where)->fetchCollection()->find()->toArray();
            }
            $data = array_merge($data, $this->data);
            if (false !== $this->controller->callback('_form_filter', $data)) {
                return $this->controller->fetch($this->tpl, ['vo' => $data]);
            }
            return $data;
        }
        // POST请求, 数据自动存库处理
        if ($this->request->isPost()) {
            $where = $this->pkValue !== null ? array_merge($this->where, [$this->pkField => $this->pkValue]) : $this->where;
            $data = array_merge($this->request->post(), $this->data);
            if (false !== $this->controller->callback('_form_filter', $data, $where)) {
                $result = $this->model->save($data,$where);
                $data = array_merge($this->model->getData(), $data);
                if (false !== $this->controller->callback('_form_result', $result, $data)) {
                    if ($result !== false) $this->controller->success(lang('Congratulations on the success of data preservation'),  '');
                    $this->controller->error('Data save failed. Please try again later');
                }
                return $result;
            }
        }
    }


}